package org.algorithm.Sort;

public class HeapSort {
    public void sort(int [] arr){
        int n =arr.length;

        for (int i = n/2-1; i >=0; i--) {
            heapify(arr,i,n);
        }

        for (int i = n-1; i >=0; i--) {
            int temp = arr[i];
            arr[i]=arr[0];
            arr[0]=temp;

            heapify(arr,0,i);
        }
    }

    static void printArray(int arr[]) {
        int n = arr.length;
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
    //大顶堆
    public void heapify(int [] arr,int i ,int n) {

        int max=i;
        int left =2*i+1;
        int right = 2*i+2;

        if (left<n && arr[max]<arr[left]){
            max=left;
        }
        if (right<n && arr[max]<arr[right]){
            max=right;
        }

        if (max!=i){

            int temp = arr[i];
            arr[i]=arr[max];
            arr[max]=temp;

            heapify(arr,max,n);
        }
    }

    public static void main(String args[]) {
        int arr[] = {12, 11, 13, 5, 6, 7};
        HeapSort ob = new HeapSort();
        ob.sort(arr);

        System.out.println("Sorted array is");
        printArray(arr);
    }
}
